package org.web.common.sso.server.controller;

import com.google.gson.Gson;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.web.common.sso.server.config.SSOServerConfig;
import org.web.common.sso.server.domain.SsoTokenDO;
import org.web.common.sso.server.helper.SSOServerConstant;
import org.web.common.sso.server.helper.redis.CacheSessionDO;
import org.web.common.sso.server.helper.redis.SsoServerRedisEnum;
import org.web.common.sso.server.service.SsoTokenService;

import javax.annotation.Resource;
import java.util.Date;
import java.util.concurrent.TimeUnit;


@Controller
@RequestMapping("test")
public class TokenControllerTest implements SSOServerConstant {

    //Logger logger = LoggerFactory.getLogger(TokenControllerTest.class);

    @Resource
    private SSOServerConfig ssoServerConfig;

    @Resource
    private SsoTokenService ssoTokenService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /***
     *
     * */
    @RequestMapping(value = "setSessionByToken", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public String setSessionByToken(String token, String accountName, String accountNum) {

        if (StringUtils.isEmpty(accountName)) {
            accountName = "luyl";
        }
        if (StringUtils.isEmpty(accountNum)) {
            accountName = "001";
        }
        CacheSessionDO cacheSessionDO = new CacheSessionDO();
        cacheSessionDO.setAccountName(accountName);
        cacheSessionDO.setAccountNum(accountNum);
        cacheSessionDO.setLastMarkTime(System.currentTimeMillis()+ssoServerConfig.getRefreshInCashTime()*ONE_MINUTE_THOUSANDTH);

        if (BooleanUtils.isTrue(ssoServerConfig.getHasRedis())) {
            stringRedisTemplate.opsForValue().set(SsoServerRedisEnum.SESSION_TOKEN.getKeyPrefix() + token, new Gson().toJson(cacheSessionDO), ssoServerConfig.getInCashTime(), TimeUnit.MINUTES);
        }

        Long expireTime = (new Date()).getTime()+ssoServerConfig.getRefreshInCashTime()*ONE_MINUTE_THOUSANDTH;
        SsoTokenDO ssoTokenDO = new SsoTokenDO();
        ssoTokenDO.setSsoToken(token);
        ssoTokenDO.setAccountName(accountName);
        ssoTokenDO.setAccountNum(accountNum);
        ssoTokenDO.setExpireTime(expireTime);
        ssoTokenService.insertSsoToken(ssoTokenDO);
        return new Gson().toJson("success");
    }

}
